package ch.subgate.chessvisualizationtrainer.utils;

import java.util.ArrayList;

import ch.subgate.chessvisualizationtrainer.R;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;

public class XmlProblemLoader {
	
	private boolean mProblemsLoaded;
	
	private ArrayList<ChessProblemCollection> mCollections;
	
	public XmlProblemLoader(Resources resources) {
		XmlResourceParser parser = resources.getXml(R.xml.chessproblems);
		
		mCollections = new ArrayList<ChessProblemCollection>();
		
		ChessProblemCollection currentCollection = null;
		ChessProblem currentProblem = null;
		
		
		try {
			while (parser.getEventType() != XmlResourceParser.END_DOCUMENT) {
				switch (parser.getEventType()) {
					case XmlResourceParser.START_TAG:
						if (parser.getName().equalsIgnoreCase("problems")) {
							currentCollection = new ChessProblemCollection(
									parser.getAttributeValue(0),
									parser.getAttributeValue(1),
									parser.getAttributeValue(2),
									parser.getAttributeValue(3));
							mCollections.add(currentCollection);
						}
						else if (parser.getName().equalsIgnoreCase("problem")) {
							currentProblem = new ChessProblem(parser.getAttributeValue(0));
							if (currentCollection != null) {
								currentCollection.addChessProblem(currentProblem);
							}
						}
						else if (parser.getName().equalsIgnoreCase("piece")) {
							if (currentProblem != null) {
								currentProblem.addPiece(
									new ChessPiece(
										parser.getAttributeValue(0),
										parser.getAttributeValue(1),
										Integer.parseInt(parser.getAttributeValue(2)),
										Integer.parseInt(parser.getAttributeValue(3))));
							}
						}
						break;
					case XmlResourceParser.END_TAG:
						if (parser.getName().equalsIgnoreCase("problems")) {
							currentCollection = null;
						}
						else if (parser.getName().equalsIgnoreCase("problem")) {
							currentProblem = null;
						}
						break;
				}
				
				parser.next();
			}
		}
		catch (Exception e) {
			// Unable to load the problems file
			mProblemsLoaded = false;
		}
		
		parser.close();
		
		mProblemsLoaded = true;
	}
	
	public ChessProblemCollection getCollection(String type) {
		if (mProblemsLoaded) {
			for (ChessProblemCollection collection : mCollections) {
				if (collection.getType().equalsIgnoreCase(type)) {
					return collection;
				}
			}
		}
		
		return null;
	}
	
	public void releaseProblemData() {
		mCollections.clear();
		mCollections = null;
		mProblemsLoaded = false;
	}
	
	public boolean getProblemsLoaded() {
		return mProblemsLoaded;
	}
}
